/*
   @Copyright:LintCode
   @Author:   tjyemail
   @Problem:  http://www.lintcode.com/problem/remove-nth-node-from-end-of-list
   @Language: C++
   @Datetime: 16-02-09 05:16
   */

/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */

class Solution {
public:
	/**
	 * @param head: The first node of linked list.
	 * @param n: An integer.
	 * @return: The head of linked list.
	 */
	ListNode *removeNthFromEnd(ListNode *head, int n) {
		// write your code here
		if (head==NULL || n==0) return head;
		ListNode H(-1), *p;
		for(p=head; n--; p=p->next);
		for(H.next=head, head=&H; p; head=head->next, p=p->next);
		p = head->next;		// to be deleted
		head->next = p->next;
		delete p;			// recommend delete
		return H.next;
	}
};
